package com.cby.library.tool.log

import android.Manifest
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.animation.DecelerateInterpolator
import android.widget.*
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.cby.library.tool.R
import com.cby.library.tool.crash.ui.CrashDetailsActivity
import com.cby.library.tool.log.CbyLogManager.Companion.instance
import com.cby.library.tool.util.*
import com.cby.library.tool.util.ToastUtils.showToast
import java.io.File

/**
 * @description: CbyLogDetailsActivity
 *
 * @author ChenBaoyang
 * @date 2021/10/25 09:43
 */
class CbyLogDetailsActivity : Activity(), View.OnClickListener {

    /**
     * Intent 传递的文件路径
     */
    companion object{
        const val INTENT_KEY_FILE_PATH = "IntentKey_FilePath"
    }

    private val handler = Handler(Looper.getMainLooper())

    /**
     * 视图控件
     */
    private lateinit var mLlBack: LinearLayout
    private lateinit var mTvShare: TextView
    private lateinit var mTvCopy: TextView
    private lateinit var mTvScreenshot: TextView
    private lateinit var mScrollViewCrashDetails: ScrollView
    private lateinit var mTvContent: TextView
    private lateinit var mIvScreenShot: ImageView
    private lateinit var mProgressView: LinearLayout
    private lateinit var mTvProgressbarMsg: TextView

    /**
     * log文件的路径
     */
    private var filePath: String? = null

    /**
     * 日志的内容
     */
    private var logContent: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_log_details)
        initFindViewById()
        initIntent()
        initListener()
        initLogData();
    }

    private fun initFindViewById() {
        mLlBack = findViewById(R.id.ll_back)
        mTvShare = findViewById(R.id.tv_share)
        mTvCopy = findViewById(R.id.tv_copy)
        mTvScreenshot = findViewById(R.id.tv_screenshot)
        mScrollViewCrashDetails = findViewById(R.id.scrollViewCrashDetails)
        mTvContent = findViewById(R.id.tv_content)
        mIvScreenShot = findViewById(R.id.iv_screen_shot)
        mProgressView = findViewById(R.id.progress_view)
        mTvProgressbarMsg = findViewById(R.id.tv_progressbar_msg)
    }

    private fun initIntent() {
        filePath = intent.getStringExtra(INTENT_KEY_FILE_PATH)
    }

    private fun initListener() {
        mLlBack.setOnClickListener(this)
        mTvShare.setOnClickListener(this)
        mTvCopy.setOnClickListener(this)
        mTvScreenshot.setOnClickListener(this)
    }

    private fun initLogData() {
        instance.getLogInfoFromFile(object : CbyLogManager.OnLogCallBack{
            override fun onLog(logInfo: String?) {
                runOnUiThread {
                    mTvContent.text = logInfo
                }
            }

        })
    }

    override fun onClick(v: View?) {
        val i = v!!.id
        if (i == R.id.ll_back) {
            finish()
        } else if (i == R.id.tv_share) {
            //先把文件转移到外部存储文件
            //请求权限
            //检查版本是否大于M
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    10086
                )
            } else {
                shareLogs()
            }
        } else if (i == R.id.tv_copy) {
            //复制
            putTextIntoClip()
            Toast.makeText(this@CbyLogDetailsActivity, "复制内容成功", Toast.LENGTH_SHORT).show()
        } else if (i == R.id.tv_screenshot) {
            //直接保存
            saveScreenShot()
        }
    }

    /**
     * 分享日志文件
     */
    private fun shareLogs() {
        //先把文件转移到外部存储文件
        val srcFile = File(filePath)
        val destFilePath = FileUtils.getCrashSharePath() + "/CrashShare.txt"
        val destFile = File(destFilePath)
        val copy = FileUtils.copyFile(srcFile, destFile)
        if (copy) {
            //分享
            ShareUtils.shareFile(this@CbyLogDetailsActivity, destFile)
        } else {
            Toast.makeText(this@CbyLogDetailsActivity, "文件保存失败", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 添加到剪切板
     */
    private fun putTextIntoClip() {
        val clipboardManager =
            this@CbyLogDetailsActivity.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
        //创建ClipData对象
        val clipData = ClipData.newPlainText("CrashLog", logContent)
        //添加ClipData对象到剪切板中
        clipboardManager.setPrimaryClip(clipData)
    }

    /**
     * 保存截图
     */
    private fun saveScreenShot() {
        showProgressLoading("正在保存截图...")
        //生成截图
        val bitmap = ScreenShotsUtils.measureSize(this, mScrollViewCrashDetails)
        Thread { savePicture(bitmap) }.start()
    }

    private fun savePicture(bitmap: Bitmap?) {
        if (bitmap != null) {
            val crashPicPath =
                FileUtils.getCrashPicPath(this@CbyLogDetailsActivity) + "/crash_pic_" + System.currentTimeMillis() + ".jpg"
            val saveBitmap = BitmapUtils.saveBitmap(this@CbyLogDetailsActivity, bitmap, crashPicPath)
            if (saveBitmap) {
                showToast("保存截图成功，请到相册查看\n路径：$crashPicPath")
                val bitmapCompress = CompressUtils.getBitmap(File(crashPicPath), 200, 200)
                handler.post {
                    dismissProgressLoading()
                    //设置图片
                    mIvScreenShot.setImageBitmap(bitmapCompress)
                    //显示
                    mIvScreenShot.visibility = View.VISIBLE
                    //设置宽高
                    val layoutParams = mIvScreenShot.layoutParams
                    layoutParams.width = ScreenUtils.getScreenWidth(this@CbyLogDetailsActivity)
                    layoutParams.height =
                        bitmapCompress.height * layoutParams.width / bitmapCompress.width
                    mIvScreenShot.layoutParams = layoutParams
                    //设置显示动画
                    mIvScreenShot.pivotX = 0f
                    mIvScreenShot.pivotY = 0f
                    val animatorSetScale = AnimatorSet()
                    val scaleX = ObjectAnimator.ofFloat(mIvScreenShot, "scaleX", 1f, 0.2f)
                    val scaleY = ObjectAnimator.ofFloat(mIvScreenShot, "scaleY", 1f, 0.2f)
                    animatorSetScale.duration = 1000
                    animatorSetScale.interpolator = DecelerateInterpolator()
                    animatorSetScale.play(scaleX).with(scaleY)
                    animatorSetScale.start()

                    //三秒后消失
                    handler.postDelayed({ mIvScreenShot.visibility = View.GONE }, 3000)
                }
            } else {
                showToast("保存截图失败")
                dismissProgressLoading()
            }
        } else {
            showToast("保存截图失败")
            dismissProgressLoading()
        }
    }

    private fun dismissProgressLoading() {
        handler.post {
            val progressView = findViewById<LinearLayout>(R.id.progress_view)
            val tvProgressbarMsg = findViewById<TextView>(R.id.tv_progressbar_msg)
            if (progressView != null) {
                progressView.visibility = View.GONE
                tvProgressbarMsg.text = "加载中..."
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        if (requestCode == 10086) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                shareLogs()
            } else {
                Toast.makeText(this@CbyLogDetailsActivity, "权限已拒绝", Toast.LENGTH_SHORT).show()
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    private fun showProgressLoading(msg: String?) {
        val progressView = findViewById<LinearLayout>(R.id.progress_view)
        val tvProgressbarMsg = findViewById<TextView>(R.id.tv_progressbar_msg)
        if (progressView != null) {
            progressView.visibility = View.VISIBLE
            tvProgressbarMsg.text = msg
            progressView.setOnClickListener { }
        }
    }
}